#include "gatewayconfigurepage.h"
#include "ui_gatewayconfigurepage.h"
#include <QJsonObject>
#include "rtupage.h"
#include "tcppage.h"

GatewayConfigurePage::GatewayConfigurePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GatewayConfigurePage)
{
    ui->setupUi(this);
}

GatewayConfigurePage::~GatewayConfigurePage()
{
    delete ui;
}

void GatewayConfigurePage::on_communicationProtocolsBox_currentIndexChanged(int index)
{
    ui->stackedWidget_2->setCurrentIndex(index);
}

QJsonObject GatewayConfigurePage::getConf()
{
    QJsonObject jsonObj;
    jsonObj.insert("gatewayName", ui->gatewayNameEdit->text());
    jsonObj.insert("address", ui->addressEdit->text());
    jsonObj.insert("communiactionProtocol", ui->communicationProtocolsBox->currentIndex());
    if (ui->communicationProtocolsBox->currentIndex() == 0)
    {
        RTUPage *rtuPage = ui->page_1;
        jsonObj.insert("serialPort", rtuPage->getSerialPort());
        jsonObj.insert("baudRate", rtuPage->getBaudRate());
        jsonObj.insert("dataBit", rtuPage->getDataBit());
        jsonObj.insert("parityBit", rtuPage->getParityBit());
        jsonObj.insert("stopBit", rtuPage->getStopBit());
    }
    else
    {
        TCPPage *tcpPage = ui->page_2;
        jsonObj.insert("ip", tcpPage->getIP());
        jsonObj.insert("port", tcpPage->getPort());
    }
    return jsonObj;
}

void GatewayConfigurePage::setConf(QJsonObject jsonObj)
{
    if (!jsonObj.contains("communiactionProtocol"))
    {
        return;
    }
    if (jsonObj.value("communiactionProtocol").toInt() == 0)
    {

    }
    else if (jsonObj.value("communiactionProtocol").toInt() == 1)
    {
        ui->stackedWidget_2->setCurrentIndex(1);
        ui->communicationProtocolsBox->setCurrentIndex(1);
        if (jsonObj.contains("gatewayName"))
        {
            ui->gatewayNameEdit->setText(jsonObj.value("gatewayName").toString());
        }
        if (jsonObj.contains("address"))
        {
            ui->addressEdit->setText(jsonObj.value("address").toString());
        }
        if (jsonObj.contains("ip"))
        {
            ui->page_2->setIP(jsonObj.value("ip").toString());
        }
        if (jsonObj.contains("port"))
        {
            ui->page_2->setPort(jsonObj.value("port").toInt());
        }
    }
}
